package com.duckygo.towerdefense.game.sprites;

import java.util.Collections;
import java.util.Comparator;

import javax.microedition.khronos.opengles.GL10;

import android.util.Log;
import android.view.MotionEvent;

import com.duckygo.towerdefense.game.scenes.SceneManager;
import com.duckygo.towerdefense.game.scenes.TowerDefenseScene;

public class IsometricLayoutSprite extends Sprite2D {

	private Comparator<Sprite> comparator = new Comparator<Sprite>() {

		@Override
		public int compare(Sprite object1, Sprite object2) {
			if (object1 instanceof Sprite2D && object2 instanceof Sprite2D)				
				return (int) (- ((Sprite2D)object2).y + ((Sprite2D)object1).y);
			
			return 0;
		}
		
	};
	private float lastX;
	private float lastY;
	
	public IsometricLayoutSprite() {
		width = 20 * 32;
		height = 20 * 32;
		
	}
	
	
	@Override
	public void draw(GL10 gl) {
	}
	
	
	@Override
	public void update(long time) {
		super.update(time);
		
		if (childrenUpdated) {
			childrenUpdated = false;
			
			Collections.sort(children, comparator);
			SceneManager.getInstance().invalidDisplayList = true;
		}
	}
	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch(event.getAction()) {
			case MotionEvent.ACTION_MOVE:
				this.x -=  lastX - event.getX();
				this.y -=  lastY - event.getY();
				
				if (this.x < - 20 * 32 + SceneManager.WIDTH) {
					this.x = -20 * 32 + SceneManager.WIDTH;
				}
				
				if (this.x > 0) {
					this.x = 0;
				}
				
				if (this.y < - 20 * 32 + SceneManager.HEIGHT) {
					this.y = -20 * 32 + SceneManager.HEIGHT;
				}
				
				if (this.y > 0) {
					this.y = 0;
				}
				
				TowerDefenseScene.terrain.x = x;
				TowerDefenseScene.terrain.y = y;
			
			case MotionEvent.ACTION_DOWN:
				lastX = event.getX();
				lastY = event.getY();
				
				return true;
			
				
			
		} 
		
		return super.onTouchEvent(event);
	}
}
